package com.hwhhhh.graduationproject.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.hwhhhh.graduationproject.domain.model.User;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * @Description detail
 * Created by Hwhhhh on 2021/3/2 19:15
 */
public class JWTUtils {
    public static final String SIGNATURE = "!SANK/3LDANFA@DFNK";   // 签名，用于加密

    /**
     * 生成token
     * @param payload 载荷，一般放id 和是否为管理员
     * @return
     */
    public static String generateToken(Map<String, String> payload){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 7); // 有效时长
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        //payload 放入载荷
        payload.forEach(builder::withClaim);

        return builder.withExpiresAt(calendar.getTime())  // 令牌过期时间
                .sign(Algorithm.HMAC256(SIGNATURE));  // 加密;
    }

    /**
     * 验证token 合法性
     * @param token
     */
    public static DecodedJWT verifyToken(String token) {
        return JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }
}
